package ru.linnenson.darshana.infrastructure.rest;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.linnenson.darshana.application.services.StorageService;
import javax.websocket.server.PathParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@Slf4j
@RestController
@RequestMapping("/api/photos")
@RequiredArgsConstructor
public class PhotoResource {

  private final StorageService storageService;

  @GetMapping("/{fileId}")
  public ResponseEntity<InputStreamResource> download(@PathVariable String fileId) throws FileNotFoundException {

    log.debug("download {} photo", fileId);

    final File file = switch (fileId) {
      case "photo1" -> ResourceUtils.getFile("classpath:photos/photo1.png");
      case "photo2" -> ResourceUtils.getFile("classpath:photos/photo2.png");
      default -> ResourceUtils.getFile("classpath:photos/sphoto1.jpg");
    };

    final MediaType mediaType = switch (fileId) {
      case "photo1", "photo2" -> MediaType.IMAGE_PNG;
      default -> MediaType.IMAGE_JPEG;
    };

    return ResponseEntity.ok()
                         .contentType(mediaType)
                         .body(new InputStreamResource(new FileInputStream(file)));
  }
}
